import axios from 'axios';
import { MessageBox, Message } from 'element-ui';
import store from '@/store';
import { getToken } from '@/utils/auth';
import targaVue from '@/main';
import defaultSettings from '@/settings'
import Cookies from 'js-cookie'

const { languageTable } = defaultSettings
const LOCALE_KEY = 'localeLanguage';

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
});

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    const localeLang = Cookies.get(LOCALE_KEY)
    config.headers['Accept-Language'] = languageTable[localeLang] // 或者你需要的语言代码
    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['Authorization'] = 'JWT ' + getToken();
    }
    // get请求映射params参数
    if (config.method === 'get' && config.params) {
      let url = config.url + '?';
      for (const propName of Object.keys(config.params)) {
        const value = config.params[propName];
        var part = encodeURIComponent(propName) + '=';
        if (value !== null && typeof value !== 'undefined') {
          if (typeof value === 'object') {
            for (const key of Object.keys(value)) {
              if (value[key] !== null && typeof value[key] !== 'undefined') {
                const params = propName + '[' + key + ']';
                const subPart = encodeURIComponent(params) + '=';
                url += subPart + encodeURIComponent(value[key]) + '&';
              }
            }
          } else {
            url += part + encodeURIComponent(value) + '&';
          }
        }
      }
      url = url.slice(0, -1);
      config.params = {};
      config.url = url;
    }
    return config;
  },
  error => {
    // do something with request error
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data;
    // result 为OK时，当前操作成功，NG时失败
    if (!res.success) {
      // 用户未认证: 50004
      // 用户认证失败: 50005
      // Token失效: 50007
      if (
        res.code === 50004 ||
        res.code === 50005 ||
        res.code === 50007
      ) {
        // 重新登录
        MessageBox.confirm(
          targaVue.$t('tokenExpired'),
          targaVue.$t('warning'),
          {
            confirmButtonText: targaVue.$t('reLogin'),
            cancelButtonText: targaVue.$t('cancel'),
            type: 'warning'
          }
        )
          .then(() => {
            store.dispatch('user/resetToken').then(() => {
              location.reload();
            });
          })
          .catch(() => {
            store.dispatch('user/resetToken').then(() => {
              location.reload();
            });
          });
      }
      return res;
    } else if (res.code === 50013) {
      targaVue.targaMessageBox('', response.msg)
    } else {
      return res;
    }
  },
  error => {
    Message({
      message: error.message,
      type: 'error',
      showClose: true,
      duration: 5 * 1000
    });
    return Promise.reject(error);
  }
);

export default service;
